﻿using System;
using System.Collections.Generic;
using UniRx;

/// <summary>
/// 单位生命周期封装
/// </summary>
public class UnitLifeCycle : UnitComponentBase
{
    private Dictionary<LifeType, Subject<long>> m_SubjectDict = new Dictionary<LifeType, Subject<long>>();
    private bool m_Active = false;

    /// <summary>
    /// 激活当前生命周期
    /// </summary>
    protected override void OnInit()
    {
        foreach (LifeType type in Enum.GetValues(typeof(LifeType)))
        {
            var subject = new Subject<long>();
            m_SubjectDict.Add(type, subject);
        }
        Observable.EveryUpdate().Subscribe(Update).AddTo(entity);
    }

    protected override void OnSpawn()
    {
        m_Active = true;
    }

    protected override void OnDespawn()
    {
        m_Active = false;
    }

    protected override void OnThaw()
    {
        m_Active = true;
    }

    protected override void OnFreeze()
    {
        m_Active = false;
    }

    private void Update(long frameCount)
    {
        if (!m_Active) return;
        foreach (var kvp in m_SubjectDict)
        {
            kvp.Value.OnNext(frameCount);
        }
    }

    /// <summary>
    /// 获取生命周期流
    /// </summary>
    public IObservable<long> GetLifeCycleStream(LifeType type)
    {
        if (!m_SubjectDict.TryGetValue(type, out var stream))
        {
            return Observable.EveryUpdate();
        }
        return stream;
    }

    public enum LifeType
    {
        /// <summary>
        /// 地形检查
        /// </summary>
        TerrainChecker,
        /// <summary>
        /// AI判定
        /// </summary>
        AICondition,
        /// <summary>
        /// AI执行
        /// </summary>
        AIExecute,
        /// <summary>
        /// 状态机判定
        /// </summary>
        FSMCondition,
        /// <summary>
        /// 状态机执行
        /// </summary>
        FSMExecute
    }
}